package org.basis.netty.chat.rpc.server.service;

import org.basis.netty.chat.util.PropertyReadUtil;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 模拟spring，由于项目中没有整合spring，所以这里模拟一下IOC
 *
 * @author Mr_wenpan@163.com 2021/9/28 4:29 下午
 */
public class ServicesFactory {

    static Properties properties;
    /**
     * 对象缓存（模拟IOC）
     */
    static Map<Class<?>, Object> map = new ConcurrentHashMap<>();

    static {
        // 读取配置文件
        try (InputStream in = PropertyReadUtil.class.getResourceAsStream("/application.properties")) {
            properties = new Properties();
            properties.load(in);
            Set<String> names = properties.stringPropertyNames();

            for (String name : names) {
                // 遍历所有的service
                if (name.endsWith("Service")) {
                    // 加载该service接口的Class对象
                    Class<?> interfaceClass = Class.forName(name);
                    // 加载该service接口的实现类的Class对象
                    Class<?> instanceClass = Class.forName(properties.getProperty(name));
                    // 保存接口类的Class以及对于的实现类的Class
                    map.put(interfaceClass, instanceClass.newInstance());
                }
            }

        } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    /**
     * 通过class对象获取该class的实现
     *
     * @param interfaceClass 接口的class对象
     * @return T 实现
     */
    public static <T> T getService(Class<T> interfaceClass) {
        return (T) map.get(interfaceClass);
    }
}